package com.czhi.lian;

import com.lmax.disruptor.EventTranslator;
import com.lmax.disruptor.dsl.Disruptor;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;

public class TradePushlisher implements Runnable {

    private static final int PUBLISH_COUNT = 10;

    private Disruptor<Trade> disruptor;
    private CountDownLatch latch;

    public TradePushlisher(Disruptor<Trade> disruptor, CountDownLatch latch) {
        this.disruptor = disruptor;
        this.latch = latch;
    }

    @Override
    public void run() {
        final TradeEventTranslator eventTranslator = new TradeEventTranslator();
        for (int i = 0; i < PUBLISH_COUNT; i++) {
            disruptor.publishEvent(eventTranslator);
        }
        latch.countDown();
    }

    private class TradeEventTranslator implements EventTranslator<Trade> {
        private ThreadLocalRandom random = ThreadLocalRandom.current();
        @Override
        public void translateTo(Trade event, long sequence) {
            this.generateTrade(event);
        }

        private void generateTrade(Trade event) {
            final double price = random.nextDouble() * 9999;
            event.setPrice(price);
        }
    }
}
